﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using NopSolutions.NopCommerce.BusinessLogic;
using NopSolutions.NopCommerce.BusinessLogic.Infrastructure;
using NopSolutions.NopCommerce.BusinessLogic.Model;
using NopSolutions.NopCommerce.BusinessLogic.SEO;
using NopSolutions.NopCommerce.BusinessLogic.Services;
using NopSolutions.NopCommerce.BusinessLogic.Utils;
using NopSolutions.NopCommerce.Common.Utils;

namespace NopSolutions.NopCommerce.Web
{
    public partial class AdvancedSearch : BaseNopFrontendPage
    {
        private IProductService _productService;
        private ISpecificationAttributeService _specsService;
        private IPictureService _pictureService;
        private ISettingService _settingService;

        private int _productImageSize = 125;
        private IList<Bundle> _bundles;

        public AdvancedSearch()
        {
            _productService = IoC.Resolve<IProductService>();
            _specsService = IoC.Resolve<ISpecificationAttributeService>();
            _pictureService = IoC.Resolve<IPictureService>();
            _settingService = IoC.Resolve<ISettingService>();
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            Load += new EventHandler(AdvancedSearch_Load);
            btnSearch.Click += new EventHandler(btnSearch_Click);
            ddlTreatment.SelectedIndexChanged += new EventHandler(ddlTreatment_SelectedIndexChanged);
            lvProducts.ItemDataBound += lvProducts_ItemDataBound;

            SEOHelper.RenderTitle(this, GetLocaleResourceString("PageTitle.AdvancedSearch"), true);
        }

        void lvProducts_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem) {
                var _product = e.Item.DataItem as Product;

                if (_product != null) {
                    var hlImageLink = e.Item.FindControl("hlImageLink") as HyperLink;
                    var hlProduct = e.Item.FindControl("hlProduct") as HyperLink;
                    var lShortDescription = e.Item.FindControl("lShortDescription") as Literal;
                    var pnlProductBundles = e.Item.FindControl("pnlProductBundles") as Panel;
                    var litBundleSave = e.Item.FindControl("litBundleSave") as Literal;
                    var lnkProductDetails = e.Item.FindControl("lnkProductDetails") as HyperLink;

                    string productURL = SEOHelper.GetProductUrl(_product);

                    lnkProductDetails.NavigateUrl = hlProduct.NavigateUrl = productURL;
                    hlProduct.Text = Server.HtmlEncode(_product.LocalizedName);

                    var picture = _product.DefaultPicture;
                    if (picture != null) {
                        hlImageLink.ImageUrl = _pictureService.GetPictureUrl(picture, this.ProductImageSize, true);
                        hlImageLink.ToolTip = String.Format(GetLocaleResourceString("Media.Product.ImageLinkTitleFormat"), _product.LocalizedName);
                        hlImageLink.Text = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), _product.LocalizedName);
                    } else {
                        hlImageLink.ImageUrl = _pictureService.GetDefaultPictureUrl(this.ProductImageSize);
                        hlImageLink.ToolTip = String.Format(GetLocaleResourceString("Media.Product.ImageLinkTitleFormat"), _product.LocalizedName);
                        hlImageLink.Text = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), _product.LocalizedName);
                    }

                    hlImageLink.NavigateUrl = productURL;
                    lShortDescription.Text = _product.LocalizedShortDescription;

                    var productBundles = _product.ProductBundles;
                    if (productBundles != null && productBundles.Count > 0) {
                        if (pnlProductBundles != null)
                            pnlProductBundles.Visible = true;

                        var rptProductBundles = e.Item.FindControl("rptProductBundles") as Repeater;
                        rptProductBundles.ItemDataBound += rptProductBundles_ItemDataBound;

                        rptProductBundles.DataSource = productBundles;
                        rptProductBundles.DataBind();
                    } else {
                        if (pnlProductBundles != null)
                            pnlProductBundles.Visible = false;
                    }

                    if (_settingService.GetSettingValueBoolean("Product.Bundle.ShowSave")) {
                        // get total bundle variants price
                        decimal bundlePrice = 0;
                        Bundles(_product.ProductId).ToList().ForEach(b => {
                            bundlePrice += b.ProductVariant.Price;
                        });
                        decimal bundleSave = bundlePrice - ProductVariant(_product).Price;

                        litBundleSave.Visible = true;
                        litBundleSave.Text = string.Format(GetLocaleResourceString("Product.Bundle.Save"), PriceHelper.FormatPrice(bundleSave));
                    } else {
                        litBundleSave.Visible = false;
                    }
                }

            }
        }

        void rptProductBundles_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) {
                var bundle = e.Item.DataItem as Bundle;
                if (bundle != null) {
                    var hlProductName = e.Item.FindControl("hlProductName") as HyperLink;
                    hlProductName.Text = bundle.ProductVariant.Product.LocalizedName;
                    hlProductName.NavigateUrl = SEOHelper.GetProductUrl(bundle.ProductVariant.Product);

                    var hlProductImage = e.Item.FindControl("hlProductImage") as HyperLink;
                    hlProductImage.ImageUrl = _pictureService.GetPictureUrl(bundle.ProductVariant.Product.DefaultPicture.PictureId, _settingService.GetSettingValueInteger("Media.Category.ThumbnailImageSize", 125), true);
                    hlProductImage.Width = Unit.Pixel(125);
                    hlProductImage.Height = Unit.Pixel(125);
                    hlProductImage.NavigateUrl = hlProductName.NavigateUrl;
                    hlProductImage.ToolTip = String.Format(GetLocaleResourceString("Media.Category.ImageLinkTitleFormat"), bundle.ProductVariant.Product.LocalizedName);
                    hlProductImage.Text = String.Format(GetLocaleResourceString("Media.Category.ImageAlternateTextFormat"), bundle.ProductVariant.Product.LocalizedName);
                }
            }
        }

        void AdvancedSearch_Load(object sender, EventArgs e)
        {
            lblNoRecords.Visible = false;

            if (!IsPostBack) {
                BindData();
            }
        }

        private void BindData()
        {
            var treatment = _specsService.GetSpecificationAttributeById(22);
            if (treatment != null) {
                var options = _specsService.GetSpecificationAttributeOptionsBySpecificationAttribute(22);
                if (options != null) {
                    ddlTreatment.DataSource = options;
                    ddlTreatment.DataTextField = "Name";
                    ddlTreatment.DataValueField = "SpecificationAttributeOptionId";
                    ddlTreatment.DataBind();
                }
            }

            var essence = _specsService.GetSpecificationAttributeById(23);
            if (essence != null) {
                var options = _specsService.GetSpecificationAttributeOptionsBySpecificationAttribute(23);
                if (options != null) {
                    chkEssence.DataSource = options;
                    chkEssence.DataTextField = "Name";
                    chkEssence.DataValueField = "SpecificationAttributeOptionId";
                    chkEssence.DataBind();

                    chkEssence.Items.Insert(0, "(Alegeti un element)");
                }
            }

            var construction = _specsService.GetSpecificationAttributeById(24);
            if (construction != null) {
                var options = _specsService.GetSpecificationAttributeOptionsBySpecificationAttribute(24);
                if (options != null) {
                    chkConstruction.DataSource = options;
                    chkConstruction.DataTextField = "Name";
                    chkConstruction.DataValueField = "SpecificationAttributeOptionId";
                    chkConstruction.DataBind();

                    chkConstruction.Items.Insert(0, "(Alegeti un element)");
                }
            }

            var identify = _specsService.GetSpecificationAttributeById(25);
            if (identify != null) {
                var options = _specsService.GetSpecificationAttributeOptionsBySpecificationAttribute(25);
                if (options != null) {
                    chkTreatment.DataSource = options;
                    chkTreatment.DataTextField = "Name";
                    chkTreatment.DataValueField = "SpecificationAttributeOptionId";
                    chkTreatment.DataBind();

                    chkTreatment.Items.Insert(0, "(Alegeti un element)");
                }
            }
        }

        void btnSearch_Click(object sender, EventArgs e)
        {
            int totalRecords = 0;
            int pageSize = 10;

            var psoFilterOption = new List<int>();
            if (!string.IsNullOrWhiteSpace(ddlTreatment.SelectedValue)) {
                psoFilterOption.Add(Convert.ToInt32(ddlTreatment.SelectedValue));
            }

            if (chkEssence.Visible) {
                if (!string.IsNullOrWhiteSpace(chkEssence.SelectedValue) && chkEssence.SelectedIndex > 0) {
                    psoFilterOption.Add(Convert.ToInt32(chkEssence.SelectedValue));
                }
            }

            if (chkConstruction.Visible) {
                if (!string.IsNullOrWhiteSpace(chkConstruction.SelectedValue) && chkConstruction.SelectedIndex > 0) {
                    psoFilterOption.Add(Convert.ToInt32(chkConstruction.SelectedValue));
                }
            }

            if (chkTreatment.Visible) {
                if (!string.IsNullOrWhiteSpace(chkTreatment.SelectedValue) && chkTreatment.SelectedIndex > 0) {
                    psoFilterOption.Add(Convert.ToInt32(chkTreatment.SelectedValue));
                }
            }

            var productCollection = _productService.GetAllProducts(0, 0, 0, false, null, null,
                string.Empty, false, pageSize, this.CurrentPageIndex,
                psoFilterOption, ProductSortingEnum.Name, out totalRecords);

            if (productCollection != null && productCollection.Count > 0) {
                lblNoRecords.Visible = false;

                lvProducts.Visible = true;
                lvProducts.DataSource = productCollection;
                lvProducts.DataBind();
            } else {
                lvProducts.Visible = false;
                lblNoRecords.Visible = true;
            }
        }

        void ddlTreatment_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlTreatment.SelectedIndex == 0) {
                pnlEssence.Visible = pnlConstruction.Visible = pnlTreatment.Visible = true;
            } else {
                pnlEssence.Visible = pnlConstruction.Visible = pnlTreatment.Visible = false;
            }
        }

        public int ProductImageSize
        {
            get
            {
                return _settingService.GetSettingValueInteger("Media.Product.ThumbnailImageSize", _productImageSize);
            }
        }

        public ProductVariant ProductVariant(Product product)
        {
            if (product != null && product.ProductVariants.Count > 0) {
                return product.ProductVariants[0];
            }
            return null;
        }

        public IList<Bundle> Bundles(int productId)
        {
            if (_bundles == null) {
                _bundles = _productService.GetAllBundlesByProductId(productId);
            }

            return _bundles;
        }

        public bool? RedirectCartAfterAddingProduct
        {
            get
            {
                if (ViewState["RedirectCartAfterAddingProduct"] == null)
                    return null;
                else
                    return (bool)ViewState["RedirectCartAfterAddingProduct"];
            }
            set
            {
                ViewState["RedirectCartAfterAddingProduct"] = value;
            }
        }

        public int CurrentPageIndex
        {
            get
            {
                int _pageIndex = CommonHelper.QueryStringInt(productsPager.QueryStringProperty);
                _pageIndex--;
                if (_pageIndex < 0)
                    _pageIndex = 0;
                return _pageIndex;
            }
        }
    }
}